<template>
	<view class="detail-container" :style="containerStyle">
		<!-- 顶部导航栏和标题 -->
		<view class="top-nav" :style="{ paddingTop: safeDistance + 'px' }">
			<view class="nav-row">
				<view class="back-button" @click="goBack">
					<text class="back-icon">←</text>
				</view>
				<view class="title-wrapper">
					<text class="main-title">{{ knowledgeDetail.title }}</text>
				</view>
			</view>
		</view>

		<!-- 核心要点Swiper -->
		<swiper class="points-swiper" :indicator-dots="false" :autoplay="false" :circular="false"
			:current="currentPointIndex" @change="onSwiperChange">
			<swiper-item v-for="(keyPoint, index) in knowledgeDetail.keyPointsFinal" :key="index">
				<view class="point-card">
					<!-- 要点说明 -->
					<view class="point-content">
						<text class="point-text">{{ keyPoint.point }}</text>
					</view>

					<!-- 代码示例 -->
					<view class="code-section">
						<view class="code-header">
							<view class="code-header-left">
								<text class="code-icon">💻</text>
								<text class="code-label">代码示例</text>
							</view>
							<view class="view-all-btn" @click="showFullScreen(keyPoint.code)">
								<text class="view-all-icon">⛶</text>
								<text class="view-all-text">查看全部</text>
							</view>
						</view>
						<view class="code-view">
							<view class="code-block">
								<rich-text class="code-text"
									:nodes="highlightCode(keyPoint.code, techCode)"></rich-text>
							</view>
						</view>
					</view>
				</view>
			</swiper-item>
		</swiper>

		<!-- 底部进度点 -->
		<view class="dots-indicator">
			<view v-for="(item, index) in knowledgeDetail.keyPointsFinal" :key="index" class="dot"
				:class="{ 'dot-active': index === currentPointIndex }" @click="switchToPoint(index)">
				<text class="dot-number">{{ index + 1 }}</text>
			</view>
		</view>

		<!-- AI助手按钮 -->
		<AiChatButton buttonText="AI助手" />
	</view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app';
import { ref, computed } from 'vue';
import { getKnowledgeCardByIdAPI, getKnowledgeCardKeyPointsAPI } from '@/services/knowledge-cards';
import { getThemeStyles } from '@/stores/theme';
import { parseKnowledgeCard } from '@/utils/knowledge';
import { highlightCode } from '@/utils/code-highlight';
import { KeyPoint, KnowledgeCardKeyPointsEntity, KnowledgeDetail } from '@/types';
import AiChatButton from '@/components/AiChatButton.vue';

// ============================================
// 响应式数据定义
// ============================================

/**
 * 知识点详情数据
 */
const knowledgeDetail = ref<KnowledgeDetail>({
	id: 0,
	title: '',
	description: '',
	icon: '',
	categoryId: '',
	categoryName: '',
	categoryIcon: '',
	difficulty: '',
	keyPointsFinal: []
});

/**
 * 当前要点索引
 */
const currentPointIndex = ref(0);

/**
 * 技术栈代码
 */
const techCode = ref<string>('');




// ============================================
// 计算属性
// ============================================

/**
 * 主题样式（响应式）
 */
const themeStyles = computed(() => getThemeStyles());

/**
 * 容器样式
 */
const containerStyle = computed(() => ({
	backgroundColor: themeStyles.value.bgPrimary
}));

/**
 * 安全距离（顶部内边距 = 安全区域 + 基础间距）
 * 用于适配刘海屏等特殊屏幕，确保内容不被遮挡
 * 
 * @returns {number} 安全距离（px）
 */
const safeDistance = computed(() => {
	// 基础间距 20px（约等于 40rpx），加上安全区域
	return (uni.getSystemInfoSync().safeAreaInsets?.top || 0) + 20;
});


// ============================================
// 生命周期钩子
// ============================================

/**
 * 页面加载（根据知识卡片ID查询数据）
 * 
 * @param {any} options - URL参数对象
 */
onLoad(async (options: any) => {
	const cardId = parseInt(options.cardId);
	techCode.value = options.techCode || 'java'; // 获取技术栈代码，默认为java

	try {
		// 显示加载提示
		uni.showLoading({
		title: '加载中...',
		mask: true
	});

		// 并行获取知识卡片基本信息和要点数据
		const [cardRes, keyPointsRes] = await Promise.all([
			getKnowledgeCardByIdAPI(cardId),
			getKnowledgeCardKeyPointsAPI(cardId)
		]);

		// 处理知识卡片基本信息
		if (cardRes.data) {
			const card = parseKnowledgeCard(cardRes.data);

			// 处理要点数据，转换为KeyPoint格式
			const keyPoints: KeyPoint[] = (keyPointsRes.data || [])
				.sort((a, b) => a.sortOrder - b.sortOrder) // 按排序字段排序
				.map((entity: KnowledgeCardKeyPointsEntity) => ({
					id: entity.id,
					point: entity.point,
					code: entity.code
				}));

			// 合并数据
			knowledgeDetail.value = {
				...card,
				keyPointsFinal: keyPoints
			};

			console.log('[Detail Page] 知识卡片加载成功:', knowledgeDetail.value);
		} else {
			uni.showToast({
				title: '未找到该知识点',
				icon: 'none',
				duration: 2000
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 2000);
		}

		uni.hideLoading();
	} catch (error) {
		console.error('[Detail Page] 加载知识点失败:', error);
		uni.hideLoading();

		uni.showToast({
		title: '加载失败，请重试',
		icon: 'none',
		duration: 2000
	});
		setTimeout(() => {
			uni.navigateBack();
		}, 2000);
	}
});


// ============================================
// 事件处理方法
// ============================================

/**
 * Swiper切换事件
 * 
 * @param {any} e - Swiper事件对象
 */
const onSwiperChange = (e: any) => {
	currentPointIndex.value = e.detail.current;
};

/**
 * 点击进度点切换到指定要点
 * 
 * @param {number} index - 要点索引
 */
const switchToPoint = (index: number) => {
	currentPointIndex.value = index;
};

/**
 * 返回列表
 */
const goBack = () => {
	uni.navigateBack();
};

/**
 * 跳转到全屏代码查看页面
 * 
 * @param {string} code - 代码内容
 */
const showFullScreen = (code: string) => {
	// 将代码内容和技术栈代码存储到本地存储
	uni.setStorageSync('fullscreenCode', code);
	uni.setStorageSync('fullscreenTechCode', techCode.value);
	// 跳转到全屏页面
	uni.navigateTo({
		url: '/pages/technologies/knowledge/code-fullscreen'
	});
};



</script>

<style lang="scss" scoped>
.detail-container {
	height: 100vh;
	display: flex;
	flex-direction: column;
	overflow: hidden;
	position: relative;
	transition: background 0.3s ease;
}

/**
	 * 顶部导航栏
	 */
.top-nav {
	flex-shrink: 0;
	padding: 20rpx 24rpx 24rpx;
	background: v-bind('themeStyles.bgPrimary');
	position: relative;
	z-index: 10;
}

.nav-row {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.back-button {
	width: 72rpx;
	height: 72rpx;
	background: v-bind('themeStyles.bgCard');
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: v-bind('themeStyles.cardShadow');
	transition: all 0.3s ease;
	flex-shrink: 0;

	&:active {
		transform: scale(0.92);
		box-shadow: v-bind('themeStyles.hoverShadow');
	}
}

.back-icon {
	font-size: 44rpx;
	color: v-bind('themeStyles.textPrimary');
	font-weight: 700;
}

.title-wrapper {
	flex: 1;
	min-width: 0;
}

.top-nav .main-title {
	font-size: 36rpx;
	font-weight: 800;
	color: v-bind('themeStyles.textPrimary');
	line-height: 1.3;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	line-clamp: 2;
	overflow: hidden;
	text-overflow: ellipsis;
}



/**
	 * 底部进度点指示器
	 */
.dots-indicator {
	flex-shrink: 0;
	display: flex;
	gap: 16rpx;
	justify-content: center;
	align-items: center;
	padding: 24rpx 0 32rpx;
	background: transparent;
	position: relative;
	z-index: 1;
}

.dot {
	width: 56rpx;
	height: 56rpx;
	border-radius: 50%;
	background: v-bind('themeStyles.bgCard');
	border: 3rpx solid v-bind('themeStyles.borderColor');
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	cursor: pointer;
	position: relative;

	&:active {
		transform: scale(0.92);
	}
}

.dot-active {
	background: v-bind('themeStyles.primaryGradient');
	border-color: v-bind('themeStyles.primaryColor');
	box-shadow: v-bind('themeStyles.buttonShadow');
	transform: scale(1.1);

	&::after {
		content: '';
		position: absolute;
		inset: -6rpx;
		border-radius: 50%;
		background: v-bind('themeStyles.primaryGradient');
		opacity: 0.2;
		filter: blur(8rpx);
		z-index: -1;
	}
}

.dot-number {
	font-size: 24rpx;
	font-weight: 700;
	color: v-bind('themeStyles.textSecondary');
	transition: color 0.3s ease;
}

.dot-active .dot-number {
	color: v-bind('themeStyles.textLight');
	text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.3);
}

/**
	 * 核心要点Swiper
	 */
.points-swiper {
	flex: 1;
	overflow: hidden;
	position: relative;
	z-index: 1;
}


/**
	 * 核心要点卡片
	 */
.point-card {
	background: v-bind('themeStyles.bgCard');
	margin: 0 24rpx;
	border-radius: 28rpx;
	box-shadow: v-bind('themeStyles.cardShadow');
	height: calc(100% - 48rpx);
	display: flex;
	flex-direction: column;
}



.point-content {
	margin-bottom: 32rpx;
	padding: 28rpx;
	background: v-bind('themeStyles.bgTertiary');
	border-radius: 20rpx;
	border-left: 6rpx solid v-bind('themeStyles.primaryColor');
	position: relative;
	flex-shrink: 0;

	&::before {
		content: '💡';
		position: absolute;
		top: 20rpx;
		right: 20rpx;
		font-size: 32rpx;
		opacity: 0.3;
	}
}

.point-text {
	font-size: 28rpx;
	color: v-bind('themeStyles.textPrimary');
	line-height: 1.8;
	font-weight: 500;
}

// ============================================
// 代码示例样式
// ============================================

.code-section {
	margin-top: 8rpx;
	flex: 1;
	display: flex;
	flex-direction: column;
}

.code-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 16rpx 24rpx;
	background: #2d3748;
	border-radius: 20rpx 20rpx 0 0;
	border-bottom: 2rpx solid rgba(255, 255, 255, 0.2);
}

.code-header-left {
	display: flex;
	align-items: center;
	gap: 12rpx;
}

.code-icon {
	font-size: 32rpx;
}

.code-label {
	font-size: 26rpx;
	font-weight: 700;
	color: #e2e8f0;
	letter-spacing: 0.5rpx;
}

.view-all-btn {
	display: flex;
	align-items: center;
	gap: 6rpx;
	padding: 8rpx 16rpx;
	background: rgba(255, 255, 255, 0.1);
	border-radius: 12rpx;
	cursor: pointer;
	transition: all 0.3s ease;
}

.view-all-icon {
	font-size: 24rpx;
	color: #e2e8f0;
}

.view-all-text {
	font-size: 22rpx;
	color: #e2e8f0;
	font-weight: 600;
}

.code-view {
	width: 100%;
	flex: 1;
	background: #2d3748;
	border-radius: 0 0 20rpx 20rpx;
	overflow: auto;
} 

.code-block {
	padding: 28rpx;
	position: relative;
	display: inline-block;
	min-width: 100%;
	box-sizing: border-box;
	overflow: auto;

	&::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		width: 6rpx;
		height: 100%;
		background: v-bind('themeStyles.primaryGradient');
	}
}

.code-text {
	font-family: 'SF Mono', 'Monaco', 'Consolas', 'Courier New', monospace;
	font-size: 26rpx;
	color: #f7fafc;
	line-height: 1.9;
	white-space: pre;
	word-break: keep-all;
	overflow-wrap: normal;
	padding-left: 20rpx;
	font-weight: 500;
	display: inline-block;
	min-width: max-content;
}

</style>